#!/bin/sh

webster_select_config()
{
  local configs=
  for config in webster-*.conf; do
    config="${config%\.*}"
    configs+=\ "${config#*\-}"
  done

  if [[ ! $configs ]];then
    echo 'No configuration file found'
    exit 1;
  fi

  PS3='Select the configuration file to use: '
  select selected in $configs;do
    if [ $selected ];then
      source `dirname $0`/webster-$selected.conf
      break
    fi
  done
}

webster_healthcheck()
{
  webster_select_config

  echo -n 'Running health checks'

  if [[ -z "$DF_B_DIR" || -z "$DF_P_DIR" || -z "$DF_DOMAIN" || -z "$DF_PATH" ]]; then {
    echo -e '\nConfiguration file is not properly setup.'
    exit 1
  }
  fi
  echo -n ' .'

  [ -w $DF_B_DIR ] || { echo -e '\nBackup directory not found or not writable.'; exit 1; };  echo -n ' .'
  [ -w $DF_P_DIR ] || { echo -e '\nProject directory not found or not writeble.'; exit 1; }; echo -n ' .'

  which unzip &>/dev/null
  if [ $? -eq 0 ]; then
    # every 6 hours
    ARCH_BASE='http://hg.insidesupport.org/DragonflyCMS-'
    # ~10 minutes cache
    #ARCH_BASE='http://dragonfly-cms.googlecode.com/archive/'
    ARCH_EXT='.zip'
  else
    echo
    echo 'unzip command not found.'
    exit 1
    # ~8 hours cache
    #ARCH_BASE='http://insidesupport.org/webster.php?dragonflycms='
    #ARCH_EXT='.tar.gz'
  fi
  echo ' .'
}

webster_maintenance()
{
  case "$1" in
    off)
      echo -n 'De-activating maintenance mode'
      local mode='0'
      ;;
    *)
      echo -n 'Activating maintenance mode'
      local mode='1'
      ;;
  esac

  mysql $DF_MYSQL_OPT -e 'UPDATE '$DF_DB_PREFIX'_config_custom SET cfg_value="'$mode'" WHERE cfg_name="global" AND cfg_field="maintenance";' || { exit 1; }; echo -n ' .'
  echo -n ' .'

  if [ -f $DF_P_DIR/cache/config_MAIN_CFG.php ]; then
    unlink $DF_P_DIR/cache/config_MAIN_CFG.php
    echo -n ' .'
  fi
  if [ -f $DF_P_DIR/cache/Dragonfly_Config ]; then
    unlink $DF_P_DIR/cache/Dragonfly_Config
    echo -n ' .'
  fi

  wget -q --spider --user-agent="$WEBSTER_UA" $DF_WGET_OPT $DF_DOMAIN$DF_PATH || { echo -e '\nCould not connect to' http://$DF_DOMAIN$DF_PATH ; exit 1; };

  echo ' . done'
  sleep 1
}

webster_set_branch()
{
  while read -er -p 'Which version to download: default, v10, v9? ' ARCH_BRANCH; do
    case $ARCH_BRANCH in
      default|v10|v9) break;;
    esac
  done
}

webster_extract()
{
  webster_download
  local archive=$DF_B_DIR/DragonflyCMS-$ARCH_BRANCH

  if [ -d $archive ]; then
    rm -rf $archive
  fi

  case "$ARCH_EXT" in
    .zip)
      unzip -tq $archive.zip || { exit 1; }
      echo 'Extracting'
      unzip -q --uo $archive.zip -d $archive || { exit 1; }
      ;;
    #.tar.gz)
      #tar zxf $archive.tar.gz -C $archive || { exit 1; }
      #;;
    *)
      exit 1;;
  esac

  echo 'Copying to destination'
  #code.google
  #local rev=`ls $archive`
  #cp -r $archive/$rev/* $DF_P_DIR || { exit 1; }
  cp -r $archive/* $DF_P_DIR || { exit 1; }
  rm -rf $archive

}

webster_download()
{
  webster_set_branch

  local archive=$DF_B_DIR/DragonflyCMS-$ARCH_BRANCH$ARCH_EXT

  if [ -f $archive ]; then
    while read -er -p 'Found cached DragonflyCMS-'$ARCH_BRANCH$ARCH_EXT', download a fresh copy? y/n: ' dl_new; do
      case $dl_new in
      y)
        unlink $archive;
        break;;
      n)
        break;;
      esac
    done
  fi

  if [ ! -f $archive ]; then
    wget --user-agent="$WEBSTER_UA" --progress=dot:binary $DF_WGET_OPT $ARCH_BASE$ARCH_BRANCH$ARCH_EXT -O $archive | grep -o "[0-9]\+%"
  fi
}

webster_ready_goto()
{
  echo -n 'Ready! Go to '
  if [ v9 == $ARCH_BRANCH ]; then
    echo $DF_DOMAIN$DF_PATH'install.php'
  else
    echo $DF_DOMAIN$DF_PATH'?install'
  fi
}

webster_check_config()
{
  echo -n 'Testing config.php'
  [ -f $DF_P_DIR'/includes/config.php' ] || { echo -e '\n'$DF_P_DIR'/includes/config.php not found.'; exit 1; }; echo -n ' .'
  while read line; do
    local b=${line%\'*}
    local b=${b##*\'}
    case $line in
      \$dbhost*)  DF_DB_HOST=$b;echo -n ' .';;
      \$dbname*)  DF_DB_NAME=$b;echo -n ' .';;
      \$dbuname*) DF_DB_UNAME=$b;echo -n ' .';;
      \$dbpass*)  DF_DB_PASS=$b;echo -n ' .';;
      \$prefix*)  DF_DB_PREFIX=$b;echo -n ' .';;
    esac
  done < $DF_P_DIR/includes/config.php

  DF_MYSQL_OPT="-h$DF_DB_HOST -u$DF_DB_UNAME -p$DF_DB_PASS -D$DF_DB_NAME"
  mysql $DF_MYSQL_OPT -e 'SELECT COUNT(*) FROM '$DF_DB_PREFIX'_config_custom;' > /dev/null
  if [ $? -gt 0 ]; then
    echo "Invalid database settings in $DF_P_DIR/includes/config.php."
    exit 1
  fi
  echo ' .'
}

webster_backup()
{
  echo -n 'Backing up'

  mysqldump -h$DF_DB_HOST -u$DF_DB_UNAME -p$DF_DB_PASS $DF_DB_NAME --add-drop-table > $DF_B_DIR/${DF_DATE}-${DF_DB_NAME}.sql
  if [ $? -gt 0 ]; then
    exit 1
  fi
  echo -n ' .'

  webster_fork sql

  if [ "$1" == 'full' ];then
    DF_DIRS=$DF_DIRS\ $DF_U_DIRS
    DF_FILES=$DF_FILES\ $DF_U_FILES
    local full=true
    local target=$DF_B_DIR/$DF_DATE-$DF_DOMAIN-full
  else
    local full=false
    local target=$DF_B_DIR/$DF_DATE-$DF_DOMAIN
  fi

  if [ -d $targer ]; then
    rm -rf $target; echo -n ' .'
  fi
  mkdir $target; echo -n ' .'

  for dir in $DF_DIRS; do
    if [ -d $DF_P_DIR/$dir ]; then
      cp -rp $DF_P_DIR/$dir $target; echo -n ' .'
    fi
  done
  for file in $DF_FILES; do
    if [ -f $DF_P_DIR/$file ]; then
      cp -p $DF_P_DIR/$file $target/; echo -n ' .'
    fi
  done

  webster_fork file $target
}

webster_restore()
{
  cd $DF_B_DIR

  local backups=
  for backup in [2]*$DF_DOMAIN*; do
    case $backup in
      2*)
        local backup="${backup%%\-*}"
        if [ -f $backup-$DF_DB_NAME.sql.gz ];then
          backups+=\ $backup
        fi
        if [ -f $backup-$DF_DOMAIN-full.tar.gz ];then
          backups+='-full'
        fi
    esac
  done

  echo "Recent backups for $DF_DOMAIN (Files and SQL):"

  local backups=`echo $backups | rev | cut -d' ' -f-9 | rev`
  if [[ ! $backups ]];then
    echo 'None found'
    exit 1;
  fi

  PS3='Select the backup date to use: '
  select selected in $backups;do
    if [ $selected ];then
      break
    fi
  done

  webster_maintenance

  local backupdate="${selected%%\-*}"
  local full="${selected/$backup/}"

  echo -n 'SQL . extracting .'
  gzip -d < $DF_B_DIR/$backupdate-$DF_DB_NAME.sql.gz > $DF_B_DIR/$backupdate-$DF_DB_NAME.sql || { exit 1; }
  echo -n ' restoring .'
  mysql -h$DF_DB_HOST -u$DF_DB_UNAME -p$DF_DB_PASS $DF_DB_NAME < $DF_B_DIR/$backupdate-$DF_DB_NAME.sql
  echo ' done'

  echo -n "Files . extracting ."
  tar zxf $DF_B_DIR/$backupdate-$DF_DOMAIN$full.tar.gz -C $DF_P_DIR/ || { exit 1; }
  echo ' done'

}

webster_fork()
{
  case "$1" in
    file)
      echo -e "\n    *compressing Files in background*"
      ;;

    sql)
      echo -e "\n    *compressing SQL in background*"
      ;;
  esac

  exec 3>&1 >> $DF_B_DIR/webster.log

  case "$1" in
    file)
      (local archive="$2"
       tar -cWf $archive.tar -C $archive ./ || { exit 1; };
       gzip -c9 < $archive.tar > $archive.tar.gz || { exit 1; };
       rm -rf $archive
       unlink $archive.tar
       exec 1>&3
       local d=`date +%Y-%m-%d\ %H:%M:%S`
       echo '['$d'] Files compressed' >> $DF_B_DIR/webster.log
       echo -e "Files compressed"
      ) & exec 1>&3
    ;;

    sql)
      (local archive=$DF_B_DIR/${DF_DATE}-${DF_DB_NAME}
       gzip -c9 < $archive.sql > $archive.sql.gz || { exit 1; };
       unlink $archive.sql
       exec 1>&3
       local d=`date +%Y-%m-%d\ %H:%M:%S`
       echo '['$d'] SQL compressed' >> $DF_B_DIR/webster.log
       echo -e "\n    *SQL compressed*"
      ) & exec 1>&3
    ;;
  esac
}

webster_usage()
{
echo "
Talking to Webster/$WEBSTER_V for DragonflyCMS

Usage: ./dragonflycms.sh [OPTION]

    --check                 Check if your configuration is correct.

    --install               Download the selected DragonflyCMS branch from Google Projects.
                            Extract content into your website installation directory.

    --upgrade               Set maintenance ON.
                            Backup database and selected files.
                            Download the selected branch.
                            Extract content into your website.

    --backup                Set maintenance ON.
                            Backup database and do a full backup of your website.
                            Set maintenance OFF.

    --restore               Set maintenance ON.
                            Restore files and database.

    --download              Download the selected branch DragonflyCMS from Google Projects.
                            Support default, v10 and v9.


    --extract               Download the selected branch.
                            Extract content into your website installation directory.

Report issues to https://code.google.com/p/nanocaiordo/
"
}

WEBSTER_V='0.6'
WEBSTER_UA='Webster/'$WEBSTER_V' ('`uname -sp`') DragonflyCMS'
DF_DATE=`date +%Y%m%d%H%M%S`
DF_WGET_OPT='--no-http-keep-alive --tries=3 --waitretry=2 --timeout=5'

case "$1" in

  --check)
    webster_healthcheck
    webster_check_config
    echo 'Ready'
    ;;

  --install)
    webster_healthcheck
    webster_extract
    webster_ready_goto
    ;;

  --upgrade)
    webster_healthcheck
    webster_check_config
    webster_maintenance
    webster_backup
    webster_extract $1
    webster_ready_goto
    ;;

  --backup)
    webster_healthcheck
    webster_check_config
    webster_maintenance
    webster_backup full
    webster_maintenance off
    echo 'Done!'
    ;;

  --restore)
    webster_healthcheck
    webster_check_config
    webster_restore
    exit 1
    ;;

  --download)
    webster_healthcheck
    webster_download
    ;;

  --extract)
    webster_healthcheck
    webster_extract
    ;;

  *)
    webster_usage
    ;;
esac

exit 0
